package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.SearchHistory;

/**
 * 
 * @author yaozhen
 * 
 */
public class SearchHistoryDao extends OrmBaseDao {

    private static SearchHistoryDao mInstance;

    private RuntimeExceptionDao<SearchHistory, String> mDao = ShuqiDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(SearchHistory.class);

    private SearchHistoryDao(Context context) {

    }

    public static synchronized SearchHistoryDao getInstance() {
        if (mInstance == null) {
            mInstance = new SearchHistoryDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    /**
     * 返回10条搜索记录
     * 
     * @return
     */
    public List<String> getSearchHistoryList() {
        QueryBuilder<SearchHistory, String> queryBuilder = mDao.queryBuilder();
        queryBuilder.orderBy("search_time", false);
        queryBuilder.limit(10L);
        List<String> result = new ArrayList<String>();
        try {
            List<SearchHistory> list = queryBuilder.query();
            for (SearchHistory searchHistory : list) {
                result.add(searchHistory.getHistory());
            }
            return result;

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 保存搜索记录
     * 
     * @param history
     */
    public void saveSearchHistory(final String history) {
        if (TextUtils.isEmpty(history)) {
            return;
        }
        SearchHistory searchHidtory = new SearchHistory();
        searchHidtory.setHistory(history);
        searchHidtory.setSearchTime(System.currentTimeMillis());
        mDao.createOrUpdate(searchHidtory);
        long count = mDao.countOf();
        if (count > 10) {
            QueryBuilder<SearchHistory, String> queryBuilder = mDao.queryBuilder();
            queryBuilder.orderBy("search_time", true);
            try {
                SearchHistory search = queryBuilder.queryForFirst();
                if (search != null && !TextUtils.isEmpty(search.getHistory())) {
                    mDao.deleteById(search.getHistory());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 删除所有搜索记录
     */
    public void clearAllSearchHistory() {
        try {
            mDao.deleteBuilder().delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
